package zl.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务器
public class Server {
	private static ServerSocket serverSocket;

	public static void main(String[] args) throws Exception {
		// 服务器监听主机端口
		serverSocket = new ServerSocket(8000);
		while (true) {
			// 等待客户请求
			System.out.println("服务器等待请求！");
			final Socket server = serverSocket.accept();
			new Thread(new Runnable() {
				public void run() {
					System.out.println("服务器接收"+server.getInetAddress()+":"+server.getPort()+"请求");
					// 获取服务器端socket的输入输出对象。输出对象通过包装避免乱码及手动flush
					BufferedReader in;
					try {
						in = new BufferedReader(new InputStreamReader(
								server.getInputStream()));
						PrintStream out = new PrintStream(
								server.getOutputStream(), true);
						while (true) {
							// 循环读取客户端发送的信息
							String str = in.readLine();
							System.out.println(str);
							// 并给出回显
							out.println("echo("+server.getInetAddress()+":"+server.getPort()+")：" + str);
							// 如客户请求bye则退出通信
							if ("bye".equalsIgnoreCase(str))
								break;
						}
						out.close();
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
		}
	}
}
